package com.gutsyzhan.dynamicdatasourcespringbootstarter.init;

import com.gutsyzhan.dynamicdatasourcespringbootstarter.properties.DataSourceProperty;
import com.gutsyzhan.dynamicdatasourcespringbootstarter.util.EncryptUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * 数据源初始化之前解密
 */
public class DecryptDataSourceInit implements DataSourceInit {
    @Override
    public void beforeCreate(DataSourceProperty dataSourceProperty) {
        //获取私钥
        String privateKey = dataSourceProperty.getPrivateKey();
        if(StringUtils.isNotEmpty(privateKey)){
            dataSourceProperty.setUsername(decrypt(privateKey, dataSourceProperty.getUsername()));
            dataSourceProperty.setPassword(decrypt(privateKey, dataSourceProperty.getPassword()));
        }
    }

    @Override
    public void afterCreate(DataSourceProperty dataSourceProperty) {

    }

    /**
     * 解密字符串
     * @param privateKey 私钥
     * @param cipherText 密文
     * @return plainText 明文
     */
    private String decrypt(String privateKey, String cipherText){
        if(StringUtils.isNotEmpty(cipherText)){
            return EncryptUtil.rsaDecrypt(cipherText, privateKey, null);
        }
        return cipherText;
    }
}
